# coding: utf-8

from django.db import models
from django.contrib.auth.models import User
from datetime import date
from orgcontrol.main.vars import PROD_POSITIONS, PRODUCTION_TYPES, PRODUCTION_TYPES_DICT
from orgcontrol.main.utils import days_in_month
from copy import copy
# Create your models here.
class ProdVolume(models.Model):
    user = models.ForeignKey(User)
    position = models.CharField(u'Вид объема', max_length = 20, choices = PROD_POSITIONS)
    index = models.IntegerField(u'Продукт')
    volume = models.IntegerField(u'Объем')
    date = models.DateField(u'Дата')

    def __unicode__(self):
        return u'{0} {1} {2} {3}'.format(self.position, PRODUCTION_TYPES_DICT[self.index], self.date, self.volume)
    class Meta:
        ordering = ['-date']
        verbose_name = u'Объем'
        verbose_name_plural = u'Объемы'
        unique_together = ('position', 'index', 'date')

    def get_by_period(self, date1, date2):
        """
        Возвращает все данные по цеху за указанный период в виде словаря day: index: volume
        """
        data = ProdVolume.objects.filter(position = self.position, date__gte=date1, date__lte=date2)
        el = {}
        for index in [one[0] for one in PRODUCTION_TYPES]: el[index] = 0
        result = {}
        #for day in range(1, days_in_month(month_no, year)+1): result[day] = copy(el)
        for day in range(1, (date2-date1).days+2 ): result[day] = copy(el)
        for one in data: result[one.date.day][one.index] = one.volume
        return result
     
    def get_by_month(self, month_no, year):
        """
        Возвращает все данные по цеху за указанные месяц и год в виде словаря day: index: volume
        """
        date1 = date(year, month_no, 1)
        date2 = date(year, month_no, days_in_month(month_no, year))
        return self.get_by_period(date1, date2)

    def get_by_year(self, year):
        """
        Возвращает все данные по цеху за указанный год в виде словаря month: volume
        """
        date1 = date(year, 1, 1)
        date2 = date(year, 12, days_in_month(12, year))
        result = {}
        for month in range(1, 13): result[month] = 0

        data = ProdVolume.objects.filter(position = self.position, date__gte=date1, date__lte=date2)
        
        for one in data:
            result[one.date.month] += one.volume

        return result


